package com.gmq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gmq.dto.DishDto;
import com.gmq.entity.Dish;
import com.gmq.entity.DishFlavor;
import com.gmq.mapper.DishMapper;
import com.gmq.service.DishFlavorService;
import com.gmq.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;


    @Override
    public DishDto dishItem(Long id) {
        DishDto dishDto = new DishDto();
        Dish byId = getById(id);
        BeanUtils.copyProperties(byId, dishDto);
        //查询口味
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(DishFlavor::getDishId, id);
        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(list);
        return dishDto;
    }

    public Dish addDishObj(DishDto dishDto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDto, dish);
        return dish;
    }

    ;

    @Override
    public void updateDish(DishDto dishDto) {
        Dish dish = addDishObj(dishDto);
        //修改菜品
        updateById(dish);
        //修改口味
        //先删除
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(DishFlavor::getDishId, dish.getId());
        dishFlavorService.remove(queryWrapper);
        //再添加新的口味数据
        for (DishFlavor flavor : dishDto.getFlavors()) {
            flavor.setDishId(dish.getId());
            dishFlavorService.save(flavor);
        }
    }

    @Override
    public void addDish(DishDto dishDto) {
        Dish dish = addDishObj(dishDto);
        save(dish);
        //添加口味
        if (dishDto.getFlavors().size() > 0) {
            for (DishFlavor flavor : dishDto.getFlavors()) {
                flavor.setDishId(dish.getId());
                dishFlavorService.save(flavor);
            }
        }
    }
}
